package com.hy.springboot.common.filter;

import com.hy.springboot.common.constant.Constant;
import com.hy.springboot.common.utils.MDCUtils;
import com.hy.springboot.common.utils.StrUtils;
import com.hy.springboot.common.utils.TraceIdUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author lccsetsun
 * @since 2024/1/31 10:56
 **/
@Component
public class RequestIdFilter implements Filter {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		try {
			HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
			String requestId = httpServletRequest.getHeader(Constant.TRACE_ID);
			if (StrUtils.isBlank(requestId)) {
				MDCUtils.set();
				TraceIdUtils.setTraceId(MDCUtils.get());
			} else {
				MDCUtils.set(requestId);
				TraceIdUtils.setTraceId(requestId);
			}
			filterChain.doFilter(servletRequest, servletResponse);
		} catch (Exception var9) {
			MDCUtils.clear();
			throw new RuntimeException(var9.getMessage());
		} finally {
			MDCUtils.clear();
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Filter.super.init(filterConfig);
	}
	@Override
	public void destroy() {
		Filter.super.destroy();
	}
}
